import axios, {type InternalAxiosRequestConfig} from 'axios'
import type {
    ApiResponse, AiAgent, ChatSession, ChatMessage,
    LoginRequest, RegisterRequest, AuthResponse, User,
    KnowledgeBase, UploadTextRequest, VoiceInfo, CreateAgentRequest
} from '@/types'

// 扩展axios配置类型
declare module 'axios' {
    interface InternalAxiosRequestConfig {
        metadata?: {
            startTime: Date
        }
    }
}

// 创建axios实例
const api = axios.create({
    // baseURL: 'http://localhost:8080/api',
    baseURL: "http://106.12.75.108:18004/api",
    timeout: 10000,
    headers: {
        'Content-Type': 'application/json'
    }
})

// 请求拦截器
api.interceptors.request.use(
    config => {
        // 添加token到请求头
        const token = localStorage.getItem('token')
        if (token) {
            config.headers.Authorization = `Bearer ${token}`
        }

        // 添加请求时间戳，用于调试
        config.metadata = {startTime: new Date()}

        return config
    },
    error => {
        console.error('请求拦截器错误:', error)
        return Promise.reject(error)
    }
)

// 响应拦截器
api.interceptors.response.use(
    response => {
        // 计算请求耗时
        if (response.config.metadata?.startTime) {
            const duration = new Date().getTime() - response.config.metadata.startTime.getTime()
            console.log(`API请求 ${response.config.url} 耗时: ${duration}ms`)
        }

        return response.data
    },
    async error => {
        console.error('API请求失败:', error)

        // 处理401未授权错误（token过期）
        if (error.response?.status === 401) {
            const token = localStorage.getItem('token')
            if (token) {
                try {
                    // 尝试刷新token
                    const refreshResponse = await api.post('/auth/refresh')
                    if (refreshResponse.status === 200) {
                        localStorage.setItem('token', refreshResponse.data.token)
                        // 重新发送原始请求
                        error.config.headers.Authorization = `Bearer ${refreshResponse.data.token}`
                        return api.request(error.config)
                    }
                } catch (refreshError) {
                    console.error('Token刷新失败:', refreshError)
                    // 刷新失败，清除本地存储并跳转到登录页
                    localStorage.removeItem('token')
                    localStorage.removeItem('user')
                    window.location.href = '/login'
                }
            } else {
                // 没有token，跳转到登录页
                window.location.href = '/login'
            }
        }

        return Promise.reject(error)
    }
)

// AI智能体相关API
export const agentApi = {
    // 获取所有启用的智能体
    getEnabledAgents(): Promise<ApiResponse<AiAgent[]>> {
        return api.get('/agents/list')
    },

    // 根据ID获取智能体详情
    getAgentById(id: number): Promise<ApiResponse<AiAgent>> {
        return api.get(`/agents/${id}`)
    },

    // 根据agentKey获取智能体详情
    getAgentByKey(agentKey: string): Promise<ApiResponse<AiAgent>> {
        return api.get(`/agents/key/${agentKey}`)
    },

    // 创建智能体
    createAgent(data: CreateAgentRequest): Promise<ApiResponse<AiAgent>> {
        return api.post('/agents', data)
    },

    // 更新智能体
    updateAgent(data: AiAgent): Promise<ApiResponse<AiAgent>> {
        return api.put('/agents', data)
    },

    // 删除智能体
    deleteAgent(id: number): Promise<ApiResponse<boolean>> {
        return api.delete(`/agents/${id}`)
    },

    // 获取音色列表
    getVoiceList(): Promise<ApiResponse<VoiceInfo[]>> {
        return api.get('/agents/voice-list')
    }
}

// 聊天相关API
export const chatApi = {
    // 创建新的聊天会话
    createSession(userId: number, agentId: number): Promise<ApiResponse<ChatSession>> {
        return api.post('/chat/session/create', null, {
            params: {userId, agentId}
        })
    },

    // 获取用户的所有会话
    getUserSessions(userId: number): Promise<ApiResponse<ChatSession[]>> {
        return api.get('/chat/session/list', {
            params: {userId}
        })
    },

    // 获取会话详情
    getSession(sessionId: string): Promise<ApiResponse<ChatSession>> {
        return api.get(`/chat/session/${sessionId}`)
    },

    // 获取会话的所有消息
    getSessionMessages(sessionId: string): Promise<ApiResponse<ChatMessage[]>> {
        return api.get(`/chat/messages/${sessionId}`)
    },

    // 删除会话
    deleteSession(sessionId: string): Promise<ApiResponse<boolean>> {
        return api.delete(`/chat/session/${sessionId}`)
    },

    // 删除消息
    deleteMessage(messageId: string): Promise<ApiResponse<boolean>> {
        return api.delete(`/chat/message/${messageId}`)
    }
}

// 认证相关API
export const authApi = {
    // 用户登录
    login(data: LoginRequest): Promise<ApiResponse<AuthResponse>> {
        return api.post('/auth/login', data)
    },

    // 用户注册
    register(data: RegisterRequest): Promise<ApiResponse<AuthResponse>> {
        return api.post('/auth/register', data)
    },

    // 获取用户信息
    getProfile(): Promise<ApiResponse<User>> {
        return api.get('/auth/profile')
    },

    // 刷新Token
    refreshToken(): Promise<ApiResponse<{ token: string }>> {
        return api.post('/auth/refresh')
    }
}

export const uploadApi = {
    uploadVideo(mp3: Blob, userId: number, agentId: number, sessionId: string, websocketSessionId: string): Promise<ApiResponse<String>> {
        const formData = new FormData()
        formData.append('audioFile', mp3, `voice_${Date.now()}.mp3`)
        formData.append('userId', userId.toString())
        formData.append('agentId', agentId.toString())
        formData.append('sessionId', sessionId)
        formData.append('websocketSessionId', websocketSessionId)
        return api.post('/voice/upload', formData, {
            headers: {
                'Content-Type': 'multipart/form-data'
            }
        })
    }
}

// 知识库相关API
export const knowledgeApi = {
    // 上传文件
    uploadFile(file: File, name: string, description: string, userId: number): Promise<ApiResponse<KnowledgeBase>> {
        const formData = new FormData()
        formData.append('file', file)
        formData.append('name', name)
        formData.append('description', description)
        formData.append('userId', userId.toString())

        return api.post('/knowledge/upload-file', formData, {
            headers: {
                'Content-Type': 'multipart/form-data'
            }
        })
    },

    // 上传文本
    uploadText(data: UploadTextRequest): Promise<ApiResponse<KnowledgeBase>> {
        return api.post('/knowledge/upload-text', data)
    },

    // 获取知识库列表
    getList(userId: number): Promise<ApiResponse<KnowledgeBase[]>> {
        return api.get('/knowledge/list', {
            params: {userId}
        })
    },

    // 获取知识库详情
    getDetail(id: number): Promise<ApiResponse<KnowledgeBase>> {
        return api.get(`/knowledge/${id}`)
    },

    // 删除知识库
    delete(id: number, userId: number): Promise<ApiResponse<boolean>> {
        return api.delete(`/knowledge/${id}`, {
            params: {userId}
        })
    }
}

export default api
